package com.vincent.kdp.ui.other;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.vincent.kdp.Activity.CostDetailActivity;
import com.vincent.kdp.Activity.DoubleDatePickerDialog;
import com.vincent.kdp.R;
import com.vincent.kdp.adapter.MemberSearchAdapter;
import com.vincent.kdp.bean.Paginator;
import com.vincent.kdp.http.RequestCallBack;
import com.vincent.kdp.ui.bean.response.MemberSearchOutput;
import com.vincent.kdp.ui.decoration.DividerItemDecoration;
import com.vincent.kdp.ui.other.repository.MemberSearchRepository;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MemberSearchActivity extends AppCompatActivity{

    @Bind(R.id.back_img)
    ImageView mBackImg;
    @Bind(R.id.toolbar_center_tv)
    TextView mToolbarCenterTv;

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.SwipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;

    @Bind(R.id.phone_et)
    EditText mPhone;
    @Bind(R.id.search_time)
    TextView mSearchTime;

    private String startTime;
    private String endTime;
    private String phone;

    public int pageNum = 1;//请求页数，默认请求第一条
    public  boolean hasNext=true;

    boolean isLoading;
    private List<MemberSearchOutput.DataBean.ListBean> data = new ArrayList<>();
    private MemberSearchAdapter adapter= new MemberSearchAdapter(this, data);
    private MemberSearchRepository memberSearchRepository=new MemberSearchRepository();

    private MemberSearchActivity thisActivity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_membersearch);
        ButterKnife.bind(this);
        mToolbarCenterTv.setText("消费搜索");
        getParam(getIntent());
        initRecycleView();
        onClickSearch();
    }

    private void getParam(Intent intent){
        String phoneOrCard=intent.getStringExtra("phoneOrCard");
        if(phoneOrCard==null){
            this.phone="";
        }else{
            this.phone=phoneOrCard;
            mPhone.setText(this.phone);

        }
    }

    private void initRecycleView() {
        thisActivity=this;

        swipeRefreshLayout.setProgressViewOffset(false, 70, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 90, getResources()
                        .getDisplayMetrics()));
        swipeRefreshLayout.setColorSchemeResources(R.color.black);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                reqData();
            }
        });
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this,LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);


            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    if(thisActivity.hasNext){
                        Log.d("test", "loading executed");

                        boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                        if (isRefreshing) {
                            adapter.notifyItemRemoved(adapter.getItemCount());
                            return;
                        }
                        if (!isLoading) {
                            isLoading = true;
                            reqData();
                        }
                    }else{

                    }

                }
            }
        });

        adapter.setOnItemClickListener(new MemberSearchAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Log.d("test", "item position = " + position);
                MemberSearchOutput.DataBean.ListBean listBean= data.get(position);
                Intent intent=new Intent(MemberSearchActivity.this, CostDetailActivity.class);
                intent.putExtra("consumeNumber",listBean.getConsumeNum());
                System.out.println("listBean.getConsumeNum()"+listBean.getConsumeNum());

                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

    }

    public void reqData() {
        memberSearchRepository.reqMemberSearchList(phone,startTime,endTime, pageNum,new RequestCallBack() {
            @Override
            public void onSuccess(Object object) {
                MemberSearchOutput memberSearchOutput = (MemberSearchOutput) object;
                Paginator paginator=memberSearchOutput.getData().getPaginator();
                if(memberSearchOutput.getData().getList().size()==0){
                    //mSpringView.setVisibility(View.GONE);
                }else if(thisActivity.hasNext){
                    data.addAll(memberSearchOutput.getData().getList());
                    swipeRefreshLayout.setRefreshing(false);
                    adapter.notifyItemRemoved(adapter.getItemCount());
                    thisActivity.pageNum=thisActivity.pageNum+1;
                    thisActivity.hasNext=paginator.isHasNextPage();
                    adapter.notifyDataSetChanged();
                }else{
                    Log.d("test", "没有更多数据" );
                    adapter.notifyItemRemoved(adapter.getItemCount());
                }
                swipeRefreshLayout.setRefreshing(false);

            }

            @Override
            public void onFalse(String msg) {
            }
        });
    }

    @OnClick(R.id.back_img)
    public void onClick() {
        this.finish();
        overridePendingTransition(com.vincent.baseapp.R.anim.fragment_left_in, com.vincent.baseapp.R.anim.fragment_right_out);
    }

    @OnClick(R.id.VIP_search)
    public void onClickSearch() {
        this.phone = mPhone.getText().toString().trim();
        if (!mSearchTime.getText().toString().trim().isEmpty()){
            String[] time = mSearchTime.getText().toString().trim().split("-");
            this.startTime = time[0];
            this.endTime = time[1];
        }
        if(this.phone==null||this.phone.isEmpty()){
            dialog("请输入手机号码");
        }else{
            reqData();
        }
    }

    @OnClick(R.id.search_time)
    public void onClickTime(){
        Calendar c = Calendar.getInstance();
        // 最后一个false表示不显示日期，如果要显示日期，最后参数可以是true或者不用输入
        new DoubleDatePickerDialog(MemberSearchActivity.this, 0, new DoubleDatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear,
                                  int startDayOfMonth, DatePicker endDatePicker, int endYear, int endMonthOfYear,
                                  int endDayOfMonth) {
                String textString = String.format("%d.%d.%d-%d.%d.%d", startYear,
                        startMonthOfYear + 1, startDayOfMonth, endYear, endMonthOfYear + 1, endDayOfMonth);
                mSearchTime.setText(textString);
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), true).show();
    }

    public void dialog(String msg){
        AlertDialog.Builder builder = new AlertDialog.Builder(MemberSearchActivity.this);
        builder.setTitle("提示");
        builder.setMessage(msg);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

}
